﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Configuration;
using System.Collections;

namespace TireService.Website
{
    public partial class Godkendtidspunkt : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get id for approval
            if (Request.QueryString["ApprovalId"] != null)
            {
                // Convert to GUID
                Guid detailguid = new Guid(Convert.ToString(Request.QueryString["ApprovalId"]));

                try
                {
                    // Instantiate data layer
                    TireServiceDB db = new TireServiceDB();

                    // Get servicecarschedule detail / booking
                    ServiceCarScheduleDetailView detail = db.ServiceCarScheduleDetailViews.SingleOrDefault(p => p.DetailGuid == detailguid);

                    // Check booking exists
                    if (detail != null)
                    {
                        // Get customer id (for double validation)
                        int CustomerId = 0;
                        try
                        {
                            CustomerId = Convert.ToInt32(Request.QueryString["CID"]);   
                        }
                        catch (Exception)
                        {
                            
                        }

                        // Validate that booking is for the right customer
                        if (CustomerId != 0 & detail.CustomerId != CustomerId)
                        {
                            throw new ArgumentException("Den valgte udkørselsdato er desværre blevet givet videre til en anden. Dette kan skyldes for sen bekræftelse eller at vi har sendt ny booking ud til dig.");
                        }

                        // Validate that booking date is not in the past (can not be approved)
                        if (detail.ScheduleDate <= DateTime.Now)
                        {
                            throw new ArgumentException("Mulighed for godkendelse af denne udkørsel er overskredet. Venligst kontakt os for en ny tid, hvis ikke allerede du har modtaget forslag til en ny booking.");
                        }

                        // Check if customer feedback is a decline of booking
                        if (Request.QueryString["Approve"] == "false")
                        {
                            // Scheduledetail has been rejected by customer
                            Customer customer = db.GetCustomer(Convert.ToInt32(detail.CustomerId));

                            // Get servicedetail data
                            lServiceDetailInfo.Text = "ServiceId: " + detail.ServiceCarScheduleDetailId + "<br>Dato: " + detail.ScheduleDate + "<br>Adresse: " + detail.ToAddress + ", " + detail.ToZipCode + " " + detail.ToCity + "<br>Klokkeslet: " + detail.StartTime.ToString() + " - " + detail.EndTime.ToString() + "<br>Kunde: " + customer.Name + "<br>Telefon1: " + customer.Phone1 + "<br>Telefon 2: " + customer.Phone2 + "<br>Email: " + customer.Email;

                            hDate.Value = detail.ScheduleDate.ToString();
                            hCustomerId.Value = customer.CustomerId.ToString();

                            // Show UI
                            pApproval.Visible = false;
                            pDecline.Visible = true;

                            // Show link to booking
                            if (customer.UserId != null)
                            {
                                lnkBooking.NavigateUrl = string.Format("~/Booking/Booking.aspx?uid={0}", customer.UserId.ToString());
                            }
                            else
                            {
                                lnkBooking.NavigateUrl = string.Format("~/Booking/Booking.aspx?did={0}&cid={1}", detail.DetailGuid.ToString(), customer.CustomerId.ToString());
                            }
                            
                            lnkBooking.Text = "Online booking";
                        }
                        else
                        {   
                            // Set detail to approved
                            ServiceCarScheduleDetail updatedetail = db.GetServiceCarScheduleDetail(detail.ServiceCarScheduleDetailId);
                            updatedetail.CustomerConfirmed = true;

                            // Commit changes to database
                            db.SubmitChanges();

                            // Update UI
                            lblScheduledate.Text = detail.ScheduleDate.ToShortDateString();
                            lblAddress.Text = detail.ToAddress;
                            lblZipCodeCity.Text = detail.ToZipCode + " " + detail.ToCity;
                            lblTimeInterval.Text = detail.StartTime.ToString() + "-" + detail.EndTime.ToString();

                            // Show message to customer
                            pApproval.Visible = true;
                            pDecline.Visible = false;
                            pMessage.Visible = false;

                            string subscriptionnumber = detail.CustomerId.ToString() + "-" + detail.SubscriptionId.ToString() + "-" + detail.CustomerSubscriptionId.ToString();

                            //// NOTE: Udkommenteret d. 24/2
                            //// Send confirmation email to customer
                            //Customer customer = db.GetCustomer(Convert.ToInt32(detail.CustomerId));
                            //SendEmail(customer.Email, customer.Name, subscriptionnumber, detail.ScheduleDate.ToShortDateString(), lblTimeInterval.Text, detail.ToAddress, detail.ToZipCode, detail.ToCity);

                            // Get customer and car
                            Customer customer = db.GetCustomer(Convert.ToInt32(detail.CustomerId));
                            Car car = db.GetCar(Convert.ToInt32(detail.CarId));

                            // Send email to customer with confirmation
                            // Prepare email
                            EmailNotificationServices emailService = new EmailNotificationServices();

                            // Send confirmation email to customer
                            emailService.Customer_ServiceDriveBookingConfirmation_SendCustomerEmail(customer.CustomerId, customer.Email, car.RegistrationNumber, customer.Name, detail.ScheduleDate.ToShortDateString(), string.Format("{0:t}", detail.StartTime) + " - " + string.Format("{0:t}", detail.EndTime), detail.ToAddress, detail.ToZipCode, detail.ToCity, null);

                        }
                    }
                    else
                    {
                        // Scheduledetail not found
                        throw new ArgumentException("Den valgte udkørselsdato kunne ikke findes i systemet.");
                    }

                    // Dispose database connection
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    // Error occured - approval could not happen
                    pApproval.Visible = false;
                    pMessage.Visible = true;

                    if ((ex) is ArgumentException)
                    {
                        // User error - arguments not valid - show error message
                        lMessage.Text = ((ArgumentException)ex).Message;
                    }
                    else
                    {
                        // System error - show general error message
                        lMessage.Text = "Fejl opstod ved godkendelse af planlagt hjulskift - venligst prøv igen eller kontakt os.";
                    }   
                }
            }
            else
            {
                // No approval id supplied - Redirect to startpage
                Response.Redirect("~/Index.aspx");
            }
        }

        // NOTE: Udkommenteret d. 24/2-2013
        ///// <summary>
        ///// Function that sends email to customer with confirmation on tirechange date
        ///// </summary>
        ///// <param name="CustomerEmail">Customer email</param>
        ///// <param name="CustomerName">Name on customer</param>
        ///// <param name="SubscriptionNumber">SubscriptionNumber for customer</param>
        ///// <param name="ScheduleDate">Date for tirechange</param>
        ///// <param name="Address">Address where tire change will happen</param>
        ///// <param name="ZipCode">ZipCode where tire change will happen</param>
        ///// <param name="City">City where tire change will happen</param>
        //private void SendEmail(string CustomerEmail, string CustomerName, string SubscriptionNumber, string ScheduleDate, string TimeSpanValue, string Address, string ZipCode, string City)
        //{
        //    string Subject = "Tak for din godkendelse - Abonnement " + SubscriptionNumber;
        //    bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
        //    Shared email = new Shared();

        //    EmailNotification.EmailNotification message = new EmailNotification.EmailNotification();

        //    //Hashtable templateVars = new Hashtable();

        //    //// Send email to customer
        //    //templateVars.Add("CustomerName", CustomerName);
        //    //templateVars.Add("ScheduleDate", ScheduleDate);
        //    //templateVars.Add("TimeSpanValue", TimeSpanValue);
        //    //templateVars.Add("Address", Address);
        //    //templateVars.Add("ZipCode", ZipCode);
        //    //templateVars.Add("City", City);
        //    //Shared.Parser parser = new Shared.Parser(Server.MapPath("~/HtmlTemplates/TidBekraeftet.htm"), templateVars);
            
        //    // Send email to customer with us on bcc
        //    email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), message.SendConfirmationOnBookingSchedule(CustomerName, ScheduleDate, TimeSpanValue, Address, ZipCode, City), Subject, true, test, ConfigurationManager.AppSettings["EmailAddress"].ToString(), null, null);
        //}

        //protected void btnSend_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
        //        bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
        //        //string message = String.Format("Hjulskift dato blev afvist<br><br>Kunde har valgt{0}<br><br>Oplysninger: <br>{1}<br><br>Kommentar: {2}", rblDate.SelectedItem.Text, lServiceDetailInfo.Text, txtComment.Text);
        //        string message = String.Format("Hjulskift dato blev afvist<br><br>Oplysninger: <br>{0}<br><br>Kommentar/Nye dato'er: {1}", lServiceDetailInfo.Text, txtComment.Text);
        //        string subject = String.Format("Hjulskift dato afvist {0} Kunde {1}", hDate.Value.ToString(), hCustomerId.Value.ToString());

        //        Shared email = new Shared();
        //        email.SendEmail(emailaddress, emailaddress, message, subject, true, test, null, null, null);

        //        pDecline.Visible = false;
        //        pApproval.Visible = false;

        //        // Show message to user
        //        lMessage.Text = "Tak for tilbagemeldingen. Vi vil hurtigst muligt planlægge et nyt hjulskift.";
        //    }
        //    catch (Exception ex)
        //    {
        //        if ((ex) is ArgumentException)
        //        {
        //            // User error - arguments not valid - show error message
        //            lMessage.Text = ((ArgumentException)ex).Message;
        //        }
        //        else
        //        {
        //            // System error - show general error message
        //            lMessage.Text = "Fejl opstod - venligst prøv igen";
        //        }
        //    }
        //}
    }
}